package com.yitao.cms.service.product;

import com.skipper.base.bean.CommonStatus;
import com.skipper.base.bean.DataOutput;
import com.skipper.base.bean.PagedInput;
import com.skipper.base.bean.PagedOutput;
import com.skipper.base.data.querydsl.PredicateBuilder;
import com.skipper.base.service.GenericEntityService;
import com.yitao.client.dto.product.ProductCommentDto;
import com.yitao.client.model.product.ProductCommentModel;
import com.yitao.client.model.product.QProductCommentModel;
import com.yitao.client.model.product.QProductInfoModel;
import com.yitao.client.model.user.QUserInfoModel;
import com.yitao.cms.constant.UserErrorEnum;
import com.yitao.cms.constant.UserSession;
import com.yitao.cms.dto.product.ProductCommentDetailDto;
import com.yitao.cms.model.operationUser.OperationUserCmsModel;
import com.yitao.cms.service.user.appUser.AppUserService;
import com.yitao.cms.utils.BaseUtils;
import com.yitao.cms.utils.DateUtils;
import com.yitao.cms.vo.product.ProductInfoVo;
import com.yitao.cms.vo.user.appUser.AppUserInfoDetailsVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Auther: wwl
 * @Date: 2019/3/11 0011 12:22
 * @Description:
 */
@Service
public class ProductCmsCommentService extends GenericEntityService<ProductCommentModel,ProductCommentDto, QProductCommentModel> {
    public ProductCmsCommentService(EntityManager entityManager){
        super(entityManager);
    }
    @Autowired
    private ProductCmsService productCmsService;
    @Autowired
    private AppUserService appUserService;
    private BaseUtils base = BaseUtils.getInstance();

    /**
     * 查询评论列表信息
     * @param request
     * @param productName
     * @param staDate
     * @param endDate
     * @param content
     * @param nickName
     * @param
     * @return
     */
    public PagedOutput findProductCommentList(HttpServletRequest request,String productName,String staDate,String endDate, String content,String nickName,Integer pageNo,Integer pageSize){
        PagedInput pagedInput = new PagedInput(pageSize,pageNo);
        //获取登录信息
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) {
            return new PagedOutput<>(pagedInput, 0, null);
        }
        QProductInfoModel productInfoModel = QProductInfoModel.productInfoModel;
        QUserInfoModel userInfoModel = QUserInfoModel.userInfoModel;
        Date staDate1 = null;
        Date endDate1 = null;
        if (!StringUtils.isEmpty(staDate) && !StringUtils.isEmpty(endDate)) {
            staDate1 = DateUtils.parseDateMilliFormat(staDate + " 00:00:00"); // 格式化日期
            endDate1 = DateUtils.parseDateMilliFormat(endDate + " 23:59:59"); // 格式化日期
        }
        final Date staDate2 = staDate1;
        final Date endDate2 = endDate1;
        final Boolean delete = false;
       List<ProductCommentModel> list = queryFactory.select(Q).from(Q).leftJoin(productInfoModel)
                .on(Q.productId.eq(productInfoModel.id))
                .leftJoin(userInfoModel).on(Q.userId.eq(userInfoModel.id))
                .where(PredicateBuilder.conjunction().
                        ifHasTextThenAnd(productName,() ->productInfoModel.productName.like("%"+productName+"%") )
                        .ifHasTextThenAnd(content,() -> Q.content.like("%"+content+"%"))
                        .ifNotNullThenAnd(userSession.getShopId(), () -> productInfoModel.shopId.eq(userSession.getShopId()))
                        .ifNotNullThenAnd(staDate2, () -> Q.createTime.between(staDate2, endDate2))
                        .ifHasTextThenAnd(nickName,() -> userInfoModel.nickName.like("%"+nickName+"%"))
                        .and(() ->Q.isDelete.eq(false))
                        .get()
                ).offset((pageNo-1)*pageSize).limit(pageSize).orderBy(Q.createTime.desc())
               .fetch();
        Long listSize = queryFactory.select(Q).from(Q).leftJoin(productInfoModel)
                .on(Q.productId.eq(productInfoModel.id))
                .leftJoin(userInfoModel).on(Q.userId.eq(userInfoModel.id))
                .where(PredicateBuilder.conjunction().
                        ifHasTextThenAnd(productName,() ->productInfoModel.productName.like("%"+productName+"%") )
                        .ifHasTextThenAnd(content,() -> Q.content.like("%"+content+"%"))
                        .ifNotNullThenAnd(staDate2, () -> Q.createTime.between(staDate2, endDate2))
                        .ifNotNullThenAnd(userSession.getShopId(), () -> productInfoModel.shopId.eq(userSession.getShopId()))
                        .ifHasTextThenAnd(nickName,() -> userInfoModel.nickName.like("%"+nickName+"%"))
                        .and(() -> Q.isDelete.eq(false))
                        .get()).fetchCount();

        List<ProductCommentDetailDto> list1 = list.stream().map(it ->{
            ProductCommentDetailDto productCommentDetailDto = new ProductCommentDetailDto();
            BeanUtils.copyProperties(it,productCommentDetailDto);
            //补充产品基本信息
            DataOutput<ProductInfoVo> productInfoVoDataOutput = productCmsService.findProductInfoById(it.getProductId());
            if (CommonStatus.SUCCESS.getCode().equals(productInfoVoDataOutput.getStatus())){
                productCommentDetailDto.setProductInfoVo(productInfoVoDataOutput.getData());
            }
            //补充昵称
            DataOutput<AppUserInfoDetailsVo>  detailsVoDataOutput = appUserService.getAppUserInfo(it.getUserId());
            if (CommonStatus.SUCCESS.getCode().equals(productInfoVoDataOutput.getStatus()) && detailsVoDataOutput.getData()!=null ){
                productCommentDetailDto.setNickName(detailsVoDataOutput.getData().getNickName());
            }
            return productCommentDetailDto;
        }).collect(Collectors.toList());
        return new PagedOutput(pagedInput,listSize,list1);
    }

    /**
     * 根据id删除产品评论信息
     * @param id
     * @return
     */
    @Transactional
    public DataOutput deleteProductCommentById(HttpServletRequest request,Long id){//获取登录信息
        OperationUserCmsModel userSession = UserSession.getUserSession(request);
        if (userSession == null) {
            return new DataOutput(UserErrorEnum.NULL_LOGIN.getCode(), UserErrorEnum.NULL_LOGIN.getDesc());
        }
        if (id!=null){
           int result = repository.updateByWhere(Q.id.eq(id), it ->
                   it.set(Q.isDelete,true)
                   .set(Q.lastUpdateBy,Long.valueOf(userSession.getId()))
                   .set(Q.lastUpdateTime,base.getNow())
           );
           if (result>0){
               return new DataOutput(CommonStatus.SUCCESS);
           }
           return new DataOutput(CommonStatus.SERVER_ERROR.getCode(),"操作失败，请重新操作!");
        }
        return new DataOutput(CommonStatus.BAD_REQUEST.getCode(),"id不能为空");

    }
    /**
     * 根据id删除产品评论信息
     * @param id
     * @return
     */
    public DataOutput getProductCommentDetailById(Long id){//获取登录信息
        ProductCommentDetailDto productCommentDetailDto = new ProductCommentDetailDto();
        if (id!=null){
          ProductCommentModel productCommentModel = queryFactory.select(Q).from(Q).where(Q.id.eq(id)).fetchFirst();
           if (productCommentModel!=null){
               BeanUtils.copyProperties(productCommentModel,productCommentDetailDto);
               //补充产品基本信息
               DataOutput<ProductInfoVo> productInfoVoDataOutput = productCmsService.findProductInfoById(productCommentModel.getProductId());
               if (CommonStatus.SUCCESS.getCode().equals(productInfoVoDataOutput.getStatus())){
                   productCommentDetailDto.setProductInfoVo(productInfoVoDataOutput.getData());
               }
               //补充昵称
               DataOutput<AppUserInfoDetailsVo>  detailsVoDataOutput = appUserService.getAppUserInfo(productCommentModel.getUserId());
               if (CommonStatus.SUCCESS.getCode().equals(productInfoVoDataOutput.getStatus()) && detailsVoDataOutput.getData()!=null ){
                   productCommentDetailDto.setNickName(detailsVoDataOutput.getData().getNickName());
               }
           }
            return new DataOutput(productCommentDetailDto);
        }
        return new DataOutput(CommonStatus.BAD_REQUEST.getCode(),"id不能为空");

    }


}
